package com.ht.web360.ObjServer.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.ht.web360.ObjServer.service.ObjService;
import com.ht.web360.base.dto.ObjInfo.dto.ObjInfoDto;
import com.ht.web360.base.dto.Res;
import com.ht.web360.base.enums.ObjType;
import com.ht.web360.base.enums.UserType;
import com.ht.web360.base.enums.dto.ObjTypeDto;
import com.ht.web360.base.utils.interfaces.RequireUserType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

@Tag(name = "对象控制器")
@RestController
@RequestMapping("obj")
public class ObjController {
    private final ObjService objService;

    public ObjController(ObjService objService) {
        this.objService = objService;
    }

    @PostMapping
    @Operation(summary = "上传对象",
            description = "header中携带 'obj-type' 代表对象类型；'obj-name' 代表对象名称",
            responses = @ApiResponse(description = "上传的对象信息"))
    @RequireUserType(UserType.User)
    public Res<ObjInfoDto> upload(
            @RequestHeader(name = "obj-type", required = false) String objType,
            @RequestHeader(name = "obj-name", required = false) String objName,
            @RequestParam("file") MultipartFile file
    ) {
        if (objType == null) {
            objType = ObjType.RectangularJpeg.getValue();
        }
        if (objName == null) {
            String name = file.getOriginalFilename();
            if (StrUtil.isBlankIfStr(name)) {
                name = "文件默认名称";
            }
            objName = name;
        }
        ObjInfoDto dto = objService.uploadObj(objName, objType, file);
        return Res.ok(dto);
    }

    @GetMapping("/{link}")
    @Operation(summary = "通过link下载对象")
    @RequireUserType(UserType.Public)
    public void download(@PathVariable("link") String link, HttpServletResponse response) {
        try (
                ServletOutputStream os = response.getOutputStream();
                InputStream is = objService.downloadObj(link);
                ) {
            IoUtil.copy(is, os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/types")
    @Operation(summary = "获取所有对象类型")
    @RequireUserType(UserType.Public)
    public Res<List<ObjTypeDto>> getObjTypes() {
        List<ObjTypeDto> list = Arrays.stream(ObjType.values())
                .map(ObjTypeDto::getInstance)
                .toList();
        return Res.ok(list);
    }
}
